import React, { useEffect, useMemo, useRef, useState } from 'react'
import * as echarts from 'echarts';
import { Row, Col } from 'antd'
import EchartsComp from 'echarts-for-react'
import { Chart } from '@antv/g2';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
type EChartsOption = echarts.EChartsOption;

const Index: React.FC = () => {
  const navigate = useNavigate()
  const el = useRef<HTMLDivElement | null>(null);
  const [x, setX] = useState([]);
  const [y, setY] = useState([]);
  const option: EChartsOption = useMemo(() => {
    return {
      xAxis: {
        type: 'category',
        data: x
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: y,
          type: "bar"
        }
      ]
    }
  }, [x, y])
  const fetchData = () => {
    axios.get('/api/list/echarts').then(resp => {
      setX(resp.data.data.x)
      setY(resp.data.data.y)
    })
  }


  useEffect(() => {
    fetchData()
  }, [])

  useEffect(() => {
    if (el.current) {
      const myChart = echarts.init(el.current);

      option && myChart.setOption(option);

      myChart.on('click', params => {
        navigate('/list?q=' + params.name)
      })
    }
  }, [x, y])


  useEffect(() => {
    // 准备数据
    const data = x.map((v, i) => {
      return { x: v, y: y[i] }
    })
    // 初始化图表实例
    const chart = new Chart({
      container: 'container',
      height: 400,
      width: 600
    });

    // 声明可视化
    chart
      .interval() // 创建一个 Interval 标记
      .data(data) // 绑定数据
      .encode('x', 'x') // 编码 x 通道
      .encode('y', 'y'); // 编码 y 通道

    // 渲染可视化
    chart.render();

    chart.on('element:click', (args) => {
      console.log(args.data.data)
      navigate('/list?q=' + args.data.data.x)
    })
  }, [x, y])


  return (
    <div>
      <Row>
        <Col span={10}>
          <div ref={el} style={{ height: 500 }}></div>
        </Col>
        <Col span={10}>
          <EchartsComp option={option} style={{ height: 500 }}></EchartsComp>
        </Col>
      </Row>
      <Row>
        <Col span={10}>
          <div id="container"></div>
        </Col>
      </Row>
    </div>
  )
}

export default Index